import {createRouter, createWebHistory} from 'vue-router';
import {getToken} from '@/utils/auth';

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
    },
    {
        path: '/',
        component: () => import('@/layouts/Layout.vue'),
        children: [
            {
                path: 'home',
                name: 'Home',
                component: () => import('@/views/Home.vue'),
                meta: {requiresAuth: true} // 需要登录权限
            },
            {
                path: 'user-manage',
                name: 'UserManage',
                component: () => import('@/views/UserManage.vue'),
                meta: {requiresAuth: true} // 需要登录权限
            },
            {
                path: 'post-manage',
                name: 'PostManage',
                component: () => import('@/views/PostManage.vue'),
                meta: {requiresAuth: true} // 需要登录权限
            },
            {
                path: 'news-manage',
                name: 'NewsManage',
                component: () => import('@/views/NewsManage.vue'),
                meta: {requiresAuth: true} // 需要登录权限
            },
            {
                path: 'appointment-manage',
                name: 'AppointmentManage',
                component: () => import('@/views/AppointmentManage.vue'),
                meta: {requiresAuth: true} // 需要登录权限
            }
        ],
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

// 路由守卫：检查登录状态
router.beforeEach((to, from, next) => {
    const isAuthenticated = getToken() !== '';
    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login');
    } else {
        next();
    }
});

export default router;
